<template>
  <div class="all">
    <div class="class">
      <div class="class-header">
        <div class="header-left">
          <div class="line"></div>
          <div class="title">项目管理</div>
          <el-input
            v-model="classSearchInput"
            placeholder="请输入项目名称"
            style="width: 150px"
            class="className"
          ></el-input>
          <el-date-picker
            v-model="startDate"
            type="date"
            placeholder="选择开始时间"
            style="width: 150px"
            class="className1"
          ></el-date-picker>
          <div class="line2"></div>
          <el-date-picker
            v-model="endDate"
            type="date"
            placeholder="选择结束时间"
            style="width: 150px"
            class="className"
          ></el-date-picker>
          <div style="position: relative">
            <el-button @click="handleSearch" class="search">搜索</el-button>
            <img src="../../assets/images/搜索.png" class="searchImg" alt="" />
          </div>
        </div>
        <div class="header-right">
          <img
            src="../../assets/images/加号.png"
            class="addmsg"
            @click="handleAdd"
            v-if="user.roleId == '1' || user.roleId == '2' || user.roleId == '3'"
          />
        </div>
      </div>
    </div>

    <div class="class-content">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column label="编号" align="center">
          <template #default="scope">
            {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="projectName" label="项目名称" align="center" />
        <el-table-column prop="leader" label="负责人" align="center" />
        <el-table-column prop="taskDay" label="工时(天)" align="center" />
        <el-table-column prop="beginTime" label="开始时间" align="center" />
        <el-table-column prop="endTime" label="结束时间" align="center" />
        <el-table-column prop="progress" label="项目进度(%)" align="center">
          <template #default="scoped">
            <el-progress type="circle" :percentage="scoped.row.progress" :width="60" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="160">
          <template #default="scope">
            <el-button
              link
              type="success"
              @click="() => updateProjectData(scope.row)"
              :disabled="
                !(
                  user.roleId == '1' ||
                  user.roleId == '2' ||
                  user.userId == scope.row.leaderId
                )
              "
              >修改</el-button
            >
            <el-button
              link
              type="danger"
              @click="() => handleDel(scope.row)"
              :disabled="
                !(
                  user.roleId == '1' ||
                  user.roleId == '2' ||
                  user.userId == scope.row.leaderId
                )
              "
              >删除</el-button
            >
            <el-button
              link
              type="primary"
              @click="() => handleDetails(scope.row)"
              :disabled="
                !(
                  user.roleId == '1' ||
                  user.roleId == '2' ||
                  UserProjectId == scope.row.projectId ||
                  user.userId == scope.row.leaderId
                ) && !disabledMap.get(scope.row.projectId)
              "
              >详情</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="page">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :current-page="currentPage"
          :page-size="pageSize"
          @current-change="handleCurrentPageChange"
        />
        <div> 
            每页
            <el-input-number
              v-model="pageSize"
              :min="1"
              :max="30"
              controls-position="right"
              @change="handleChange"
            />条
        </div>

      </div>
    </div>

    <!-- 添加项目 -->
    <el-dialog v-model="dialogVisible" title="添加项目" width="400px" :show-close="false">
      <el-form
        :model="formData"
        :rules="rules"
        ref="formRef"
        label-width="100px"
        hide-required-asterisk
      >
        <el-row>
          <el-form-item label="项目名称" prop="projectName">
            <el-input v-model="formData.projectName" placeholder="请输入项目名称" />
          </el-form-item>
          <el-form-item label="负责人" prop="leaderId">
            <!-- 下拉框 -->
            <el-select
              v-model="formData.leaderId"
              placeholder="请选择负责人"
              @change="leaderChange"
              :disabled="user.roleId == '3'"
            >
              <el-option
                v-for="item in teacherData"
                :key="item.userId"
                :label="item.userName"
                :value="item.userId"
              />
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="开始时间" prop="beginTime">
            <el-date-picker
              v-model="formData.beginTime"
              type="date"
              placeholder="请选择开始时间"
              style="width: 200px"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker
              v-model="formData.endTime"
              type="date"
              placeholder="请选择结束时间"
              style="width: 200px"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="项目工期" prop="taskDay">
            <el-input v-model="formData.taskDay" placeholder="请输入项目工期" />
          </el-form-item>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false" class="cancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm" class="confirm">确认</el-button>
      </template>
    </el-dialog>
     <!-- 修改项目 -->
     <el-dialog v-model="dialogVisible1" title="修改项目" width="400px" :show-close="false">
      <el-form
        :model="formData"
        :rules="rules"
        ref="formRef"
        label-width="100px"
        hide-required-asterisk
      >
        <el-row>
          <el-form-item label="项目名称" prop="projectName">
            <el-input v-model="formData.projectName" placeholder="请输入项目名称" />
          </el-form-item>
          <el-form-item label="负责人" prop="leaderId">
            <!-- 下拉框 -->
            <el-select
              v-model="formData.leaderId"
              placeholder="请选择负责人"
              @change="leaderChange"
            >
              <el-option
                v-for="item in (user.roleId == '1' || user.roleId == '2') ? teacherData : projectMember"
                :key="item.userId"
                :label="item.userName"
                :value="item.userId"
              />
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="开始时间" prop="beginTime">
            <el-date-picker
              v-model="formData.beginTime"
              type="date"
              placeholder="请选择开始时间"
              style="width: 200px"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker
              v-model="formData.endTime"
              type="date"
              placeholder="请选择结束时间"
              style="width: 200px"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="项目工期" prop="taskDay">
            <el-input v-model="formData.taskDay" placeholder="请输入项目工期" />
          </el-form-item>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible1 = false" class="cancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm1" class="confirm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { getProject, addProject, getTeacher, getSubProject ,updateProject,deleteProject} from '../api/Project'
import { getProjectMember } from '../api/ProjectDetails'

//分页
const currentPage = ref(1) // 当前页码
const pageSize = ref(7) // 每页显示条数
const total = ref(0) // 总条数
//表格数据
const tableData = ref([])
//搜索框
const classSearchInput = ref('')
//日期
const startDate = ref(null)
const endDate = ref(null)

//项目组成员列表
const projectMember = ref([])
import dayjs from 'dayjs' // 引入 dayjs 库
//本地数据
const user = JSON.parse(localStorage.getItem('user'))

//判断是否可以点击详情
const disabledMap = ref(new Map()) // 存储每个项目的禁用状态

//判断是否有项目id
const UserProjectId = ref('')
if (JSON.parse(localStorage.getItem('userProjectId'))) {
  UserProjectId.value = JSON.parse(localStorage.getItem('userProjectId'))
}

//获取项目接口
async function fetchData() {
  let data = {
    pageIndex: currentPage.value,
    pageSize: pageSize.value,
  }
  if (classSearchInput.value) {
    data.projectName = classSearchInput.value
  }
  if (startDate.value && endDate.value) {
    data.beginTime = startDate.value
    data.endTime = endDate.value
  }
  await getProject('projectList', data).then((res) => {
    if (res.code === 200) {
      tableData.value = res.dataset.projectList
      total.value = res.dataset.pageCount * pageSize.value
    }
  })
  const promises = tableData.value.map(async (row) => {
    const isDisabled = await calculateDisabled(row)
    //存储每个项目的禁用状态
    disabledMap.value.set(row.projectId, isDisabled)
  })
  await Promise.all(promises)
}

async function calculateDisabled(row) {
  const res = await getSubProject('childLeaderId', { projectId: row.projectId })
  if (res.code === 200) {
    for (let i = 0; i < res.dataset.length; i++) {
      if (res.dataset[i].leaderId == user.userId) {
        return true
      }
    }
    return false
  }
}

// 处理当前页变化
const handleCurrentPageChange = (value) => {
  currentPage.value = value
  fetchData()
}

// 获取项目成员接口
async function fetchProjectMember(projectId) {
  
  const res = await getProjectMember('groupList', { projectId: projectId })
  if (res.code === 200) {
    console.log(res.dataset);
    projectMember.value = res.dataset
  }
}

const validateSearchTime = () => {
  if (startDate.value && endDate.value) {
    const start = dayjs(startDate.value)
    const end = dayjs(endDate.value)
    if (end.isBefore(start)) {
      ElMessage.warning('开始时间必须在结束时间之前')
      return false
    }
  }
  return true
}

//搜索
function handleSearch() {
  if (!validateSearchTime()) {
    return
  }
  currentPage.value = 1 // 重置页码为1
  if ((startDate.value && endDate.value) || (!startDate.value && !endDate.value)) {
    fetchData()
  } else {
    ElMessage({
      message: '开始时间和结束时间必须全都有或者全都为空',
      type: 'warning',
    })
  }
}

// 详情
const router = useRouter()
//跳转详情页面
const handleDetails = (row) => {
  //输出当前行数据
  router.push({
    path: '/allTotal/ProjectDetails',
    query: {
      projectId: row.projectId,
      leaderId: row.leaderId,
      beginTime: row.beginTime,
      endTime: row.endTime,
    },
  })
}

//老师列表
const teacherData = ref([])

//获取老师列表
function fetchTeacher() {
  getTeacher('teacherList').then((res) => {
    if (res.code === 200) {
      teacherData.value = res.dataset
    }
  })
}

//负责人下拉框发生变化
function leaderChange() {
  if(user.roleId=='1' || user.roleId=='2'){
    const selectedLeader = teacherData.value.find(
      (teacher) => teacher.userId === formData.value.leaderId
    )
    if (selectedLeader) {
      formData.value.leader = selectedLeader.userName
    }
  }else{
    const selectedLeader = projectMember.value.find(
      (teacher) => teacher.userId === formData.value.leaderId
    )
    if (selectedLeader) {
      formData.value.leader = selectedLeader.userName
    }
  }
}

//添加项目接口
function addProjectData() {
  let data = {
    projectName: formData.value.projectName,
    leaderId: formData.value.leaderId,
    beginTime: formData.value.beginTime,
    endTime: formData.value.endTime,
    taskDay: formData.value.taskDay,
    leader: formData.value.leader,
  }
  addProject('addProject', data).then((res) => {
    if (res.code === 200) {
      ElMessage.success('添加成功')
      fetchData()
    }
  })
}

// 添加项目模态框
// 新增：模态框显示状态
const dialogVisible = ref(false)
// 新增：表单数据
const formData = ref({
  leaderId: '',
  projectName: '',
  leader: '',
  taskDay: '',
  beginTime: '',
  endTime: '',
})
// 新增：表单引用
const formRef = ref(null)

//开始时间必须在结束时间之前
const validateBeginTime = (rule, value, callback) => {
  if (formData.value.endTime && value) {
    const endTime = dayjs(formData.value.endTime)
    const beginTime = dayjs(value)
    if (endTime.isBefore(beginTime)) {
      callback(new Error('开始时间必须在结束时间之前'))
    } else {
      callback()
    }
  } else {
    callback()
  }
}

// 结束时间必须在开始时间之后
const validateEndTime = (rule, value, callback) => {
  if (formData.value.beginTime && value) {
    const beginTime = dayjs(formData.value.beginTime)
    const endTime = dayjs(value)
    if (endTime.isBefore(beginTime)) {
      callback(new Error('结束时间必须在开始时间之后'))
    } else {
      callback()
    }
  } else {
    callback()
  }
}
// 计算工期
const calculateTaskDay = () => {
  if (formData.value.beginTime && formData.value.endTime) {
    const beginTime = dayjs(formData.value.beginTime)
    const endTime = dayjs(formData.value.endTime)
    const days = endTime.diff(beginTime, 'day')
    formData.value.taskDay = days
  }
}

// 计算结束时间
const calculateEndTime = () => {
  if (formData.value.beginTime && formData.value.taskDay) {
    const beginTime = dayjs(formData.value.beginTime)
    const endTime = beginTime.add(parseInt(formData.value.taskDay), 'day')
    formData.value.endTime = endTime.format('YYYY-MM-DD')
  }
}

// 计算开始时间
const calculateBeginTime = () => {
  if (formData.value.endTime && formData.value.taskDay) {
    const endTime = dayjs(formData.value.endTime)
    const beginTime = endTime.subtract(parseInt(formData.value.taskDay), 'day')
    formData.value.beginTime = beginTime.format('YYYY-MM-DD')
  }
}

// 新增：表单验证规则
const rules = ref({
  leaderId: [{ required: true, message: '请选择负责人', trigger: 'blur' }],
  projectName: [
    { required: true, message: '请输入项目名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
  ],
  taskDay: [
    { required: true, message: '请输入任务工期', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (formData.value.beginTime && value) {
          calculateEndTime()
        } else if (formData.value.endTime && value) {
          calculateBeginTime()
        }
        callback()
      },
      trigger: 'blur',
    },
  ],
  beginTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' },
    { validator: validateBeginTime, trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (value && formData.value.endTime) {
          calculateTaskDay()
        } else if (value && formData.value.taskDay) {
          calculateEndTime()
        }
        callback()
      },
      trigger: 'change',
    },
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' },
    { validator: validateEndTime, trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (value && formData.value.beginTime) {
          calculateTaskDay()
        } else if (value && formData.value.taskDay) {
          calculateBeginTime()
        }
        callback()
      },
      trigger: 'change',
    },
  ],
})

// 新增：点击添加项目按钮方法
const handleAdd = () => {
  if(charu.value){
    teacherData.value.pop()
    charu.value=false
  }
  if (formRef.value) {
    //清空验证
    formRef.value.clearValidate()
  }
  // 清空表单数据
  formData.value = {
    leaderId: '',
    projectName: '',
    leader: '',
    taskDay: '',
    beginTime: '',
    endTime: '',
  }
  if (user.roleId == '3') {
    formData.value.leaderId= user.userId
    leaderChange(user.userId)
  }
  dialogVisible.value = true
}

// 新增：点击确认按钮方法
const handleConfirm = () => {
  // 提交表单逻辑
  formRef.value.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm('是否确认添加项目？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          addProjectData()
          dialogVisible.value = false
        })
        .catch(() => {
          ElMessage.info('已取消添加项目')
        })
    }
  })
}

//上来就调用接口
onMounted(() => {
  fetchData()
  fetchTeacher()
})
//修改项目
const dialogVisible1 = ref(false)

const charu=ref(false)

const qita=ref(false)

//修改项目
async function updateProjectData(row) {
    dialogVisible1.value = true
    if(user.roleId=='3' || user.roleId=='4'){
      if(qita.value){
        teacherData.value.pop()
        qita.value=false
      }
      await fetchProjectMember(row.projectId)
      //遍历项目成员列表，找到对应的负责人
      const selectedLeader = projectMember.value.find(
        (member) => member.userId === user.userId
      )
      if(!selectedLeader){
        //如果没有负责人，就把负责人插入到下拉框中
        projectMember.value.push({ userId: user.userId, userName: user.userName })
        qita.value=true
      }
    }
    if(charu.value){
      teacherData.value.pop()
      charu.value=false
    }
    console.log('修改数据',row);
    //遍历老师列表，找到对应的老师，如果找不到把负责人插入到下拉框中
    const selectedLeader = teacherData.value.find(
      (teacher) => teacher.userId === row.leaderId
    )
    if (!selectedLeader) {
      teacherData.value.push({ userId: row.leaderId, userName: row.leader })
      charu.value=true
    }
    formData.value = {...row}
}

//修改项目接口
function updateProjectData1() {
  let data = {
    projectId: formData.value.projectId,
    projectName: formData.value.projectName,
    leaderId: formData.value.leaderId,
    beginTime: formData.value.beginTime,
    endTime: formData.value.endTime,
    taskDay: formData.value.taskDay,
    leader: formData.value.leader,
  }
  updateProject('updateProject', data).then((res) => {
    if (res.code === 200) {
      ElMessage.success('修改成功')
      fetchData()
    }else{
      ElMessage.error('修改失败')
    }
  })
}
// 修改：点击确认按钮方法
const handleConfirm1 = () => {
  // 提交表单逻辑
  formRef.value.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm('是否确认修改项目？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        updateProjectData1()
        dialogVisible1.value = false
      }).catch(() => {
        ElMessage.info('已取消修改项目')
      })
    }
  })
}

//删除项目接口
function deleteProjectData(row) {
  deleteProject('deleteProject', { projectId: row.projectId }).then((res) => {
    if (res.code === 200) {
      ElMessage.success('删除成功')
      fetchData()
    }else{
      ElMessage.error('删除失败')
    }
  })
}
//删除项目
function handleDel(row) {
  ElMessageBox.confirm('是否确认删除项目？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deleteProjectData(row)
  }).catch(() => {
    ElMessage.info('已取消删除项目')
  })
}

function handleChange(){
  currentPage.value = 1 // 重置页码为1
  fetchData()
}

</script>

<style scoped>
.class {
  width: 90%;
  height: 10%;
  margin-bottom: 20px;
  margin-top: 20px;
}
/* 头部左侧 */
.header-left {
  display: flex;
  align-items: center;
  margin-left: 40px;
}
.line {
  width: 2px;
  height: 20px;
  background-color: #007bff;
}
.title {
  padding-left: 10px;
  font-size: 20px;
  margin-right: 20px;
}
.className {
  margin-right: 10px;
}
.line2 {
  width: 10px;
  height: 2px;
  margin-left: 5px;
  margin-right: 5px;
  background-color: #9b9b9b;
}
:deep(.className .el-input__wrapper) {
  border-radius: 12px !important;
}
:deep(.className1 .el-input__wrapper) {
  border-radius: 12px !important;
}
.search {
  background-color: #0f6ab1;
  color: #fff;
  border: none;
  margin-left: 10px;
  border-radius: 16px;
  padding: 0;
  padding-right: 15px;
  padding-left: 36px;
}
.searchImg {
  position: absolute;
  top: 8px;
  left: 25px;
}
/* 头部右侧 */
.header-right {
  display: flex;
  align-items: center;
  margin-right: 40px;
}
.addmsg {
  width: 25px;
  height: 25px;
}

/* 表格区域 */
.class-content {
  width: 90%;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

/* 表格数据 */
:deep(.el-table thead th) {
  background-color: #fbfcff !important;
}
:deep(.el-table .cell) {
  color: black;
}
:deep(.details1) {
  margin-left: 55px;
}
/* 分页 */
.page {
  margin-top: 50px;
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  align-items: center;

}
/* 分页背景色 */
:deep(.el-pager .is-active) {
  background-color: #0f6ab1 !important;
}

/* 模态框 */
:deep(.el-overlay .el-overlay-dialog) {
  position: absolute;
}
:deep(.el-overlay) {
  position: absolute;
}
:deep(.el-dialog) {
  padding: 0px;
  width: 800px;
}
:deep(.el-dialog header span) {
  display: inline-block;
  width: 100%;
  background-color: #0f6ab1;
  height: 40px;
  color: white;
  font-size: 15px;
  text-align: center;
  line-height: 40px;
}
:deep(.el-dialog__body) {
  display: flex;
  justify-content: center;
}
:deep(.el-select) {
  width: 200px;
}
:deep(.el-dialog__footer) {
  text-align: center;
  padding-bottom: 20px;
}
:deep(.confirm) {
  margin-left: 50px;
  background-color: #0f6ab1;
}
:deep(.cancel) {
  background-color: #0f6ab1;
  color: white;
}
</style>